<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/18
 * Time: 10:35
 */

namespace app\admin\model;


use app\admin\model\GoodsSpecItem as GoodsSpecItemModel;

class GoodsSpec extends BaseModel
{

    public function item()
    {
        return $this->hasMany('GoodsSpecItem','spec_id','id');
    }


    public function addEdi($params,$tag=false){
        $this->startTrans();
        $res = $this->allowField(true)->isUpdate($tag)->save($params);
        if($res === false){
            $this->rollback();
            return ['error'=>1,'msg'=>'规格操作失败!'];
        }
        if(!empty($params['spec_values'])){
            $spec_values = [];
            $params['spec_values'] = explode(PHP_EOL,$params['spec_values']);
            foreach($params['spec_values'] as $k=>$v){
                if(!empty($v)){
                    $spec_values[$k]['name'] = $v;
                    $spec_values[$k]['spec_id'] = $this->id;
                }
            }
            if(!empty($spec_values)){
                $goodsSpecItemModel = new GoodsSpecItemModel();
                $goodsSpecItemModel->startTrans();
                if($tag == true){
                    GoodsSpecItemModel::where(['spec_id'=>$params['id']])->delete();
                }
                $res = $goodsSpecItemModel->allowField(true)->isUpdate(false)->insertAll($spec_values);
                if($res === false){
                    $goodsSpecItemModel->rollback();
                    return ['error'=>1,'msg'=>'规格属性值操作失败!'];
                }
            }
            $goodsSpecItemModel->commit();
        }
        $this->commit();
        return ['error'=>0,'msg'=>'操作成功!'];
    }
}